﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Diagnostics.Contracts;
using System.ComponentModel.Composition;

namespace Kooboo.Commerce.Repositories
{
    [Export(typeof(IPromotionLogRepository))]
    public partial class EntityRepositories : IPromotionLogRepository
    {
    
        public IQueryable<IPromotionLog> PromotionLogs
        {
            get
            {
                return this.DataReaderContext.PromotionLogs;
            }
        }

        public void Post(IPromotionLog promotionLog)
        {
            Contract.Requires(promotionLog != null);

            var item = new PromotionLog()
            {
                Discount = promotionLog.Discount,
                OrderId = promotionLog.Order.Id,
                OrderItemId = (promotionLog.OrderItem != null ? new Nullable<int>(promotionLog.OrderItem.Id) : null),
                ProductId = (promotionLog.Product != null ? new Nullable<int>(promotionLog.Product.Id) : null),
                PromotionRuleId = promotionLog.PromotionRule.Id,
                Remark = promotionLog.Remark,
                UserName = promotionLog.UserName
            };

            this.DataWriterContext.PromotionLogs.InsertOnSubmit(item);
            this.DataWriterContext.SubmitChanges();
        }

        public void Put(IPromotionLog promotionLog)
        {
            Contract.Requires(promotionLog != null);

            var item = this.DataWriterContext.PromotionLogs
                .Where(i => i.Id == promotionLog.Id)
                .FirstOrDefault();

            if (item == null)
            {
                throw new KeyNotFoundException("PromotionLog: " + promotionLog.Id);

            }

            item.Discount = promotionLog.Discount;
            item.OrderId = promotionLog.Order.Id;
            item.OrderItemId = (promotionLog.OrderItem != null ? new Nullable<int>(promotionLog.OrderItem.Id) : null);
            item.ProductId = (promotionLog.Product != null ? new Nullable<int>(promotionLog.Product.Id) : null);
            item.PromotionRuleId = promotionLog.PromotionRule.Id;
            item.Remark = promotionLog.Remark;
            item.UserName = promotionLog.UserName;

            this.DataWriterContext.SubmitChanges();
        }

        public void Delete(IPromotionLog promotionLog)
        {
            if (promotionLog != null)
            {
                var item = this.DataWriterContext.PromotionLogs
                .Where(i => i.Id == promotionLog.Id)
                .FirstOrDefault();

                if (item != null)
                {
                    this.DataWriterContext.PromotionLogs.DeleteOnSubmit(item);
                    this.DataWriterContext.SubmitChanges();
                }
            }
        }

    }
}
